---
title: 函数和作用域机制
description: 深入理解 Python 和 JavaScript 的函数定义、调用机制、作用域规则和闭包概念，掌握高阶函数和函数式编程模式。
---

# 函数和作用域机制

函数是程序设计的核心构建块，Python 和 JavaScript 都支持函数式编程，但在函数定义、作用域规则和闭包行为上有重要差异。本模块将帮助你理解这些差异，掌握在 JavaScript 中有效使用函数的技巧。

## 函数定义和调用

### 基本函数定义

<PythonEditor title="函数定义方式" compare={true}>
```python !! py
# Python 函数定义

# 1. 基本函数定义
def greet(name):
    """问候函数"""
    return f"Hello, {name}!"

# 2. 带默认参数的函数
def greet_with_title(name, title="Mr./Ms."):
    """带默认参数的问候函数"""
    return f"Hello, {title} {name}!"

# 3. 可变参数函数
def sum_numbers(*args):
    """计算可变数量数字的和"""
    return sum(args)

def print_info(**kwargs):
    """打印关键字参数信息"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# 4. 混合参数函数
def complex_function(required, default="default", *args, **kwargs):
    """复杂参数函数"""
    print(f"Required: {required}")
    print(f"Default: {default}")
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

# 函数调用示例
print(greet("Alice"))
print(greet_with_title("Bob", "Dr."))
print(sum_numbers(1, 2, 3, 4, 5))

print_info(name="Charlie", age=30, city="New York")

complex_function("test", "custom", 1, 2, 3, extra="value")

# 5. Lambda 函数
square = lambda x: x ** 2
add = lambda x, y: x + y

print(f"Square of 5: {square(5)}")
print(f"Add 3 and 4: {add(3, 4)}")

# 6. 函数作为第一类对象
def multiply(x, y):
    return x * y

# 函数赋值
operation = multiply
result = operation(4, 5)
print(f"Operation result: {result}")

# 函数作为参数
def apply_operation(a, b, func):
    return func(a, b)

result = apply_operation(6, 7, multiply)
print(f"Apply operation: {result}")
```

```javascript !! js
// JavaScript 函数定义

// 1. 函数声明
function greet(name) {
    // 函数体
    return `Hello, ${name}!`;
}

// 2. 函数表达式
const greetExpression = function(name) {
    return `Hello, ${name}!`;
};

// 3. 箭头函数（ES6+）
const greetArrow = (name) => {
    return `Hello, ${name}!`;
};

// 简化箭头函数
const greetSimple = name => `Hello, ${name}!`;

// 4. 带默认参数的函数（ES6+）
function greetWithTitle(name, title = "Mr./Ms.") {
    return `Hello, ${title} ${name}!`;
}

// 5. 可变参数函数（Rest parameters）
function sumNumbers(...args) {
    return args.reduce((sum, num) => sum + num, 0);
}

function printInfo(requiredParam, ...otherArgs) {
    console.log(`Required: ${requiredParam}`);
    console.log(`Other args: ${otherArgs}`);
}

// 6. 对象解构参数
function printUserInfo({name, age, city = "Unknown"}) {
    console.log(`Name: ${name}, Age: ${age}, City: ${city}`);
}

// 函数调用示例
console.log(greet("Alice"));
console.log(greetWithTitle("Bob", "Dr."));
console.log(sumNumbers(1, 2, 3, 4, 5));

printInfo("required", "arg1", "arg2", "arg3");
printUserInfo({name: "Charlie", age: 30, city: "New York"});

// 7. 立即执行函数表达式（IIFE）
const result = (function(x, y) {
    return x + y;
})(5, 3);
console.log(`IIFE result: ${result}`);

// 8. 函数作为第一类对象
function multiply(x, y) {
    return x * y;
}

// 函数赋值
const operation = multiply;
const result2 = operation(4, 5);
console.log(`Operation result: ${result2}`);

// 函数作为参数
function applyOperation(a, b, func) {
    return func(a, b);
}

const result3 = applyOperation(6, 7, multiply);
console.log(`Apply operation: ${result3}`);

// 9. 方法定义（在对象中）
const calculator = {
    add(a, b) {
        return a + b;
    },
    
    subtract: function(a, b) {
        return a - b;
    },
    
    multiply: (a, b) => a * b  // 注意：箭头函数没有自己的 this
};

console.log(`Calculator add: ${calculator.add(10, 5)}`);
console.log(`Calculator subtract: ${calculator.subtract(10, 5)}`);
console.log(`Calculator multiply: ${calculator.multiply(10, 5)}`);
```
</PythonEditor>

### 函数参数处理

<PythonEditor title="参数处理机制" compare={true}>
```python !! py
# Python 参数处理

# 1. 位置参数和关键字参数
def process_data(data, format_type="json", verbose=False, **options):
    """处理数据的函数"""
    print(f"Data: {data}")
    print(f"Format: {format_type}")
    print(f"Verbose: {verbose}")
    if options:
        print(f"Options: {options}")

# 不同的调用方式
process_data("sample_data")
process_data("sample_data", "xml")
process_data("sample_data", verbose=True)
process_data("sample_data", format_type="csv", verbose=True, encoding="utf-8")

# 2. 强制关键字参数（Python 3+）
def create_user(name, *, age, email):
    """创建用户，age 和 email 必须使用关键字参数"""
    return {
        "name": name,
        "age": age,
        "email": email
    }

# 必须使用关键字参数
user = create_user("Alice", age=25, email="alice@example.com")
print(f"Created user: {user}")

# 3. 参数解包
def add_three_numbers(a, b, c):
    return a + b + c

numbers = [1, 2, 3]
result = add_three_numbers(*numbers)  # 解包列表
print(f"Sum with unpacking: {result}")

# 字典解包
def introduce(name, age, city):
    return f"I'm {name}, {age} years old, from {city}"

person_info = {"name": "Bob", "age": 30, "city": "London"}
introduction = introduce(**person_info)  # 解包字典
print(introduction)

# 4. 类型注解（Type hints）
from typing import List, Dict, Optional, Union, Callable

def calculate_average(numbers: List[float]) -> float:
    """计算平均值"""
    if not numbers:
        return 0.0
    return sum(numbers) / len(numbers)

def process_callback(data: List[int], callback: Callable[[int], int]) -> List[int]:
    """处理数据并应用回调函数"""
    return [callback(item) for item in data]

# 使用类型注解的函数
average = calculate_average([1.5, 2.5, 3.5])
print(f"Average: {average}")

processed = process_callback([1, 2, 3, 4], lambda x: x * 2)
print(f"Processed: {processed}")

# 5. 函数重载（使用 functools.singledispatch）
from functools import singledispatch

@singledispatch
def process_value(value):
    """默认处理函数"""
    return f"Unknown type: {type(value)}"

@process_value.register
def _(value: int):
    return f"Integer: {value * 2}"

@process_value.register
def _(value: str):
    return f"String: {value.upper()}"

@process_value.register
def _(value: list):
    return f"List length: {len(value)}"

# 测试函数重载
print(process_value(42))
print(process_value("hello"))
print(process_value([1, 2, 3]))
print(process_value(3.14))
```

```javascript !! js
// JavaScript 参数处理

// 1. 参数默认值和解构
function processData(data, {
    formatType = "json",
    verbose = false,
    encoding = "utf-8",
    ...options
} = {}) {
    console.log(`Data: ${data}`);
    console.log(`Format: ${formatType}`);
    console.log(`Verbose: ${verbose}`);
    console.log(`Encoding: ${encoding}`);
    if (Object.keys(options).length > 0) {
        console.log(`Options: ${JSON.stringify(options)}`);
    }
}

// 不同的调用方式
processData("sample_data");
processData("sample_data", {formatType: "xml"});
processData("sample_data", {verbose: true});
processData("sample_data", {
    formatType: "csv",
    verbose: true,
    compression: "gzip"
});

// 2. 参数验证和类型检查
function createUser(name, {age, email, ...options} = {}) {
    // 参数验证
    if (typeof name !== 'string' || !name.trim()) {
        throw new Error("Name must be a non-empty string");
    }
    
    if (typeof age !== 'number' || age < 0) {
        throw new Error("Age must be a non-negative number");
    }
    
    if (typeof email !== 'string' || !email.includes('@')) {
        throw new Error("Email must be a valid string");
    }
    
    return {
        name,
        age,
        email,
        ...options
    };
}

// 使用对象参数模拟关键字参数
const user = createUser("Alice", {
    age: 25,
    email: "alice@example.com",
    city: "New York"
});
console.log(`Created user: ${JSON.stringify(user)}`);

// 3. 扩展运算符和剩余参数
function addThreeNumbers(a, b, c) {
    return a + b + c;
}

const numbers = [1, 2, 3];
const result = addThreeNumbers(...numbers);  // 扩展数组
console.log(`Sum with spread: ${result}`);

// 对象扩展
function introduce({name, age, city, ...otherInfo}) {
    const intro = `I'm ${name}, ${age} years old, from ${city}`;
    if (Object.keys(otherInfo).length > 0) {
        return `${intro}. Additional info: ${JSON.stringify(otherInfo)}`;
    }
    return intro;
}

const personInfo = {
    name: "Bob",
    age: 30,
    city: "London",
    profession: "Developer",
    hobby: "Reading"
};
const introduction = introduce(personInfo);
console.log(introduction);

// 4. 函数重载模拟
function processValue(value) {
    // 根据类型分发
    switch (typeof value) {
        case 'number':
            return `Number: ${value * 2}`;
        case 'string':
            return `String: ${value.toUpperCase()}`;
        case 'object':
            if (Array.isArray(value)) {
                return `Array length: ${value.length}`;
            } else if (value === null) {
                return "Null value";
            } else {
                return `Object keys: ${Object.keys(value).length}`;
            }
        case 'boolean':
            return `Boolean: ${!value}`;
        default:
            return `Unknown type: ${typeof value}`;
    }
}

// 测试函数重载
console.log(processValue(42));
console.log(processValue("hello"));
console.log(processValue([1, 2, 3]));
console.log(processValue({a: 1, b: 2}));
console.log(processValue(true));

// 5. 更高级的参数处理
class AdvancedFunctions {
    // 方法重载模拟
    static calculate(...args) {
        if (args.length === 1) {
            return args[0] ** 2;  // 平方
        } else if (args.length === 2) {
            return args[0] + args[1];  // 加法
        } else if (args.length === 3) {
            return args[0] * args[1] * args[2];  // 乘法
        } else {
            throw new Error("Unsupported number of arguments");
        }
    }
    
    // 柯里化函数
    static curry(fn) {
        return function curried(...args) {
            if (args.length >= fn.length) {
                return fn.apply(this, args);
            } else {
                return function(...args2) {
                    return curried.apply(this, args.concat(args2));
                };
            }
        };
    }
}

// 测试高级功能
console.log(AdvancedFunctions.calculate(5));        // 25
console.log(AdvancedFunctions.calculate(3, 4));     // 7
console.log(AdvancedFunctions.calculate(2, 3, 4));  // 24

// 柯里化示例
const multiply = (a, b, c) => a * b * c;
const curriedMultiply = AdvancedFunctions.curry(multiply);
const multiplyBy2 = curriedMultiply(2);
const multiplyBy2And3 = multiplyBy2(3);
console.log(multiplyBy2And3(4));  // 24
```
</PythonEditor>

## 作用域和变量查找

### 作用域规则比较

<PythonEditor title="作用域机制" compare={true}>
```python !! py
# Python 作用域规则（LEGB）

# 全局变量
global_var = "I'm global"

def outer_function():
    # 封闭作用域（Enclosing scope）
    outer_var = "I'm in outer function"
    
    def inner_function():
        # 局部作用域（Local scope）
        local_var = "I'm local"
        
        # 访问不同作用域的变量
        print(f"Local: {local_var}")
        print(f"Outer: {outer_var}")
        print(f"Global: {global_var}")
        
        # 内建作用域（Built-in scope）
        print(f"Built-in len function: {len}")
    
    inner_function()
    return inner_function

# 测试作用域
outer_function()

# 1. global 关键字
counter = 0

def increment_global():
    global counter
    counter += 1
    print(f"Global counter: {counter}")

increment_global()
increment_global()

# 2. nonlocal 关键字
def make_counter():
    count = 0
    
    def increment():
        nonlocal count
        count += 1
        return count
    
    return increment

counter_func = make_counter()
print(f"Counter: {counter_func()}")  # 1
print(f"Counter: {counter_func()}")  # 2
print(f"Counter: {counter_func()}")  # 3

# 3. 作用域和变量遮蔽
name = "Global Alice"

def test_shadowing():
    name = "Local Bob"  # 遮蔽全局变量
    print(f"Inside function: {name}")

test_shadowing()
print(f"Outside function: {name}")

# 4. 列表推导式的作用域（Python 3+）
x = "global x"
squares = [x**2 for x in range(5)]  # x 在推导式中是局部的
print(f"After comprehension: {x}")  # 仍然是 "global x"

# 5. 函数定义时的作用域捕获
functions = []
for i in range(3):
    # 使用默认参数捕获当前值
    functions.append(lambda x=i: x)

for func in functions:
    print(func())  # 0, 1, 2

# 6. 变量生命周期
def create_closure():
    data = [1, 2, 3, 4, 5]
    
    def get_data():
        return data  # data 在闭包中保持活跃
    
    return get_data

getter = create_closure()
print(f"Closure data: {getter()}")

# 7. 模块级别的作用域
# __name__ 是模块级别的内建变量
if __name__ == "__main__":
    print("This is the main module")

# 导入的作用域
import math
from datetime import datetime

print(f"Math pi: {math.pi}")
print(f"Current time: {datetime.now()}")
```

```javascript !! js
// JavaScript 作用域规则

// 全局作用域
var globalVar = "I'm global";
let globalLet = "I'm also global";
const globalConst = "I'm global too";

function outerFunction() {
    // 函数作用域
    var outerVar = "I'm in outer function";
    let outerLet = "I'm also in outer";
    
    function innerFunction() {
        // 内部函数作用域
        var localVar = "I'm local";
        let localLet = "I'm also local";
        
        // 访问不同作用域的变量
        console.log(`Local var: ${localVar}`);
        console.log(`Local let: ${localLet}`);
        console.log(`Outer var: ${outerVar}`);
        console.log(`Outer let: ${outerLet}`);
        console.log(`Global var: ${globalVar}`);
        console.log(`Global let: ${globalLet}`);
    }
    
    innerFunction();
    return innerFunction;
}

// 测试作用域
outerFunction();

// 1. var vs let vs const 的作用域差异
function scopeTest() {
    console.log("\n=== Scope Test ===");
    
    if (true) {
        var varVariable = "var in block";
        let letVariable = "let in block";
        const constVariable = "const in block";
    }
    
    console.log(`var outside block: ${varVariable}`);  // 可访问
    // console.log(letVariable);  // ReferenceError
    // console.log(constVariable);  // ReferenceError
}

scopeTest();

// 2. 变量提升（Hoisting）
function hoistingTest() {
    console.log("\n=== Hoisting Test ===");
    
    console.log(`var before declaration: ${typeof hoistedVar}`);  // undefined
    // console.log(hoistedLet);  // ReferenceError (temporal dead zone)
    
    var hoistedVar = "I'm hoisted";
    let hoistedLet = "I'm not hoisted";
    
    console.log(`var after declaration: ${hoistedVar}`);
    console.log(`let after declaration: ${hoistedLet}`);
}

hoistingTest();

// 3. 闭包和变量捕获
let counter = 0;

function incrementGlobal() {
    counter++;
    console.log(`Global counter: ${counter}`);
}

incrementGlobal();
incrementGlobal();

// 创建闭包计数器
function makeCounter() {
    let count = 0;
    
    return function() {
        count++;
        return count;
    };
}

const counterFunc = makeCounter();
console.log(`Counter: ${counterFunc()}`);  // 1
console.log(`Counter: ${counterFunc()}`);  // 2
console.log(`Counter: ${counterFunc()}`);  // 3

// 4. 变量遮蔽
const name = "Global Alice";

function testShadowing() {
    const name = "Local Bob";  // 遮蔽外部变量
    console.log(`Inside function: ${name}`);
}

testShadowing();
console.log(`Outside function: ${name}`);

// 5. 循环中的闭包问题
console.log("\n=== Loop Closure Issues ===");

// 问题：使用 var
const functionsVar = [];
for (var i = 0; i < 3; i++) {
    functionsVar.push(function() {
        return i;  // 所有函数都引用同一个 i
    });
}

console.log("Using var:");
functionsVar.forEach(func => console.log(func()));  // 3, 3, 3

// 解决方案1：使用 let
const functionsLet = [];
for (let i = 0; i < 3; i++) {
    functionsLet.push(function() {
        return i;  // 每个 i 都是独立的
    });
}

console.log("Using let:");
functionsLet.forEach(func => console.log(func()));  // 0, 1, 2

// 解决方案2：使用 IIFE
const functionsIIFE = [];
for (var i = 0; i < 3; i++) {
    functionsIIFE.push((function(index) {
        return function() {
            return index;
        };
    })(i));
}

console.log("Using IIFE:");
functionsIIFE.forEach(func => console.log(func()));  // 0, 1, 2

// 6. 模块作用域（ES6 模块）
// 在实际模块中，顶级声明不会污染全局作用域
const moduleVariable = "I'm module-scoped";

// 7. this 关键字的作用域
const obj = {
    name: "Object",
    
    regularMethod: function() {
        console.log(`Regular method this: ${this.name}`);
        
        const innerFunction = function() {
            console.log(`Inner function this: ${this.name}`);  // undefined
        };
        innerFunction();
        
        const arrowFunction = () => {
            console.log(`Arrow function this: ${this.name}`);  // "Object"
        };
        arrowFunction();
    },
    
    arrowMethod: () => {
        console.log(`Arrow method this: ${this.name}`);  // undefined
    }
};

console.log("\n=== This Binding ===");
obj.regularMethod();
obj.arrowMethod();

// 8. 严格模式下的作用域
function strictModeTest() {
    'use strict';
    
    // 在严格模式下，this 不会自动绑定到全局对象
    function innerFunc() {
        console.log(`Strict mode this: ${this}`);  // undefined
    }
    
    innerFunc();
}

strictModeTest();
```
</PythonEditor>

## 闭包和高阶函数

### 闭包机制对比

<PythonEditor title="闭包机制" compare={true}>
```python !! py
# Python 闭包机制

# 1. 基本闭包
def create_multiplier(factor):
    """创建一个乘法器闭包"""
    def multiplier(number):
        return number * factor  # factor 被闭包捕获
    return multiplier

# 使用闭包
double = create_multiplier(2)
triple = create_multiplier(3)

print(f"Double 5: {double(5)}")  # 10
print(f"Triple 4: {triple(4)}")  # 12

# 2. 闭包修改外部变量
def create_accumulator(initial=0):
    """创建累加器闭包"""
    total = [initial]  # 使用列表避免 nonlocal
    
    def accumulate(value):
        total[0] += value
        return total[0]
    
    def get_total():
        return total[0]
    
    def reset():
        total[0] = initial
    
    # 返回函数对象，附加方法
    accumulate.get_total = get_total
    accumulate.reset = reset
    
    return accumulate

acc = create_accumulator(10)
print(f"Accumulate 5: {acc(5)}")    # 15
print(f"Accumulate 3: {acc(3)}")    # 18
print(f"Current total: {acc.get_total()}")  # 18
acc.reset()
print(f"After reset: {acc.get_total()}")    # 10

# 3. 使用 nonlocal 的闭包
def create_counter(start=0, step=1):
    """创建计数器闭包"""
    count = start
    
    def increment():
        nonlocal count
        count += step
        return count
    
    def decrement():
        nonlocal count
        count -= step
        return count
    
    def get_value():
        return count
    
    # 返回字典包含多个函数
    return {
        'increment': increment,
        'decrement': decrement,
        'get_value': get_value
    }

counter = create_counter(0, 2)
print(f"Initial: {counter['get_value']()}")      # 0
print(f"Increment: {counter['increment']()}")    # 2
print(f"Increment: {counter['increment']()}")    # 4
print(f"Decrement: {counter['decrement']()}")    # 2

# 4. 闭包捕获循环变量（常见陷阱）
def create_functions_wrong():
    """错误的闭包创建方式"""
    functions = []
    for i in range(3):
        functions.append(lambda: i)  # 所有 lambda 共享同一个 i
    return functions

def create_functions_correct():
    """正确的闭包创建方式"""
    functions = []
    for i in range(3):
        functions.append(lambda x=i: x)  # 使用默认参数捕获 i 的当前值
    return functions

print("\n错误方式:")
wrong_funcs = create_functions_wrong()
for func in wrong_funcs:
    print(func())  # 2, 2, 2

print("\n正确方式:")
correct_funcs = create_functions_correct()
for func in correct_funcs:
    print(func())  # 0, 1, 2

# 5. 装饰器中的闭包
def timer_decorator(func):
    """计时装饰器"""
    import time
    
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} took {end_time - start_time:.4f} seconds")
        return result
    
    return wrapper

@timer_decorator
def slow_function():
    """模拟慢函数"""
    import time
    time.sleep(0.1)
    return "Done!"

result = slow_function()
print(f"Result: {result}")

# 6. 工厂函数和配置闭包
def create_validator(min_length=0, max_length=float('inf'), pattern=None):
    """创建验证器闭包"""
    import re
    
    compiled_pattern = re.compile(pattern) if pattern else None
    
    def validate(value):
        if not isinstance(value, str):
            return False, "Value must be a string"
        
        if len(value) < min_length:
            return False, f"Value too short (min: {min_length})"
        
        if len(value) > max_length:
            return False, f"Value too long (max: {max_length})"
        
        if compiled_pattern and not compiled_pattern.match(value):
            return False, f"Value doesn't match pattern: {pattern}"
        
        return True, "Valid"
    
    return validate

# 创建不同的验证器
email_validator = create_validator(5, 100, r'^[^@]+@[^@]+\.[^@]+$')
password_validator = create_validator(8, 50, r'^(?=.*[A-Za-z])(?=.*\d)')

# 测试验证器
test_email = "user@example.com"
test_password = "mypass123"

email_valid, email_msg = email_validator(test_email)
password_valid, password_msg = password_validator(test_password)

print(f"Email '{test_email}': {email_valid} - {email_msg}")
print(f"Password '{test_password}': {password_valid} - {password_msg}")
```

```javascript !! js
// JavaScript 闭包机制

// 1. 基本闭包
function createMultiplier(factor) {
    // factor 被闭包捕获
    return function(number) {
        return number * factor;
    };
}

// 使用箭头函数的简化版本
const createMultiplierArrow = factor => number => number * factor;

// 使用闭包
const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(`Double 5: ${double(5)}`);  // 10
console.log(`Triple 4: ${triple(4)}`);  // 12

// 2. 闭包修改外部变量
function createAccumulator(initial = 0) {
    let total = initial;
    
    function accumulate(value) {
        total += value;
        return total;
    }
    
    // 为函数添加额外方法
    accumulate.getTotal = () => total;
    accumulate.reset = () => {
        total = initial;
    };
    
    return accumulate;
}

const acc = createAccumulator(10);
console.log(`Accumulate 5: ${acc(5)}`);      // 15
console.log(`Accumulate 3: ${acc(3)}`);      // 18
console.log(`Current total: ${acc.getTotal()}`);  // 18
acc.reset();
console.log(`After reset: ${acc.getTotal()}`);    // 10

// 3. 使用对象返回多个闭包函数
function createCounter(start = 0, step = 1) {
    let count = start;
    
    return {
        increment() {
            count += step;
            return count;
        },
        
        decrement() {
            count -= step;
            return count;
        },
        
        getValue() {
            return count;
        },
        
        reset() {
            count = start;
        }
    };
}

const counter = createCounter(0, 2);
console.log(`Initial: ${counter.getValue()}`);      // 0
console.log(`Increment: ${counter.increment()}`);   // 2
console.log(`Increment: ${counter.increment()}`);   // 4
console.log(`Decrement: ${counter.decrement()}`);   // 2

// 4. 闭包与循环变量（常见陷阱和解决方案）
console.log("\n=== Loop Variable Closure ===");

// 问题：使用 var（延迟绑定）
function createFunctionsWrongVar() {
    const functions = [];
    for (var i = 0; i < 3; i++) {
        functions.push(function() {
            return i;  // 所有函数共享同一个 i
        });
    }
    return functions;
}

// 解决方案1：使用 let（块级作用域）
function createFunctionsWithLet() {
    const functions = [];
    for (let i = 0; i < 3; i++) {
        functions.push(function() {
            return i;  // 每个 i 都是独立的
        });
    }
    return functions;
}

// 解决方案2：使用 IIFE 立即执行函数
function createFunctionsWithIIFE() {
    const functions = [];
    for (var i = 0; i < 3; i++) {
        functions.push((function(index) {
            return function() {
                return index;
            };
        })(i));
    }
    return functions;
}

// 解决方案3：使用 bind
function createFunctionsWithBind() {
    const functions = [];
    function returnValue(value) {
        return value;
    }
    
    for (var i = 0; i < 3; i++) {
        functions.push(returnValue.bind(null, i));
    }
    return functions;
}

// 测试不同方案
console.log("Using var (wrong):");
createFunctionsWrongVar().forEach(func => console.log(func()));  // 3, 3, 3

console.log("Using let:");
createFunctionsWithLet().forEach(func => console.log(func()));   // 0, 1, 2

console.log("Using IIFE:");
createFunctionsWithIIFE().forEach(func => console.log(func()));  // 0, 1, 2

console.log("Using bind:");
createFunctionsWithBind().forEach(func => console.log(func()));  // 0, 1, 2

// 5. 模块模式（Module Pattern）
const MyModule = (function() {
    // 私有变量和函数
    let privateVariable = 0;
    const privateArray = [];
    
    function privateFunction(value) {
        return value * 2;
    }
    
    // 公共 API
    return {
        // 公共方法
        addItem(item) {
            privateArray.push(item);
            privateVariable++;
        },
        
        getCount() {
            return privateVariable;
        },
        
        getItems() {
            return [...privateArray];  // 返回副本
        },
        
        processItem(item) {
            return privateFunction(item);
        },
        
        clear() {
            privateArray.length = 0;
            privateVariable = 0;
        }
    };
})();

// 使用模块
MyModule.addItem("item1");
MyModule.addItem("item2");
console.log(`Module count: ${MyModule.getCount()}`);  // 2
console.log(`Module items: ${MyModule.getItems()}`);  // ["item1", "item2"]
console.log(`Process 5: ${MyModule.processItem(5)}`); // 10

// 6. 高级闭包：柯里化和偏函数应用
function curry(fn) {
    return function curried(...args) {
        if (args.length >= fn.length) {
            return fn.apply(this, args);
        } else {
            return function(...args2) {
                return curried.apply(this, args.concat(args2));
            };
        }
    };
}

// 原始函数
function add(a, b, c) {
    return a + b + c;
}

// 柯里化版本
const curriedAdd = curry(add);

// 不同的使用方式
console.log(curriedAdd(1)(2)(3));     // 6
console.log(curriedAdd(1, 2)(3));     // 6
console.log(curriedAdd(1)(2, 3));     // 6

// 创建专用函数
const add10 = curriedAdd(10);
const add10And5 = add10(5);
console.log(add10And5(3));  // 18

// 7. 记忆化（Memoization）闭包
function memoize(fn) {
    const cache = new Map();
    
    return function(...args) {
        const key = JSON.stringify(args);
        
        if (cache.has(key)) {
            console.log(`Cache hit for ${key}`);
            return cache.get(key);
        }
        
        console.log(`Computing for ${key}`);
        const result = fn.apply(this, args);
        cache.set(key, result);
        
        return result;
    };
}

// 斐波那契数列（递归版本）
const fibonacci = memoize(function(n) {
    if (n < 2) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
});

console.log(`Fibonacci(10): ${fibonacci(10)}`);
console.log(`Fibonacci(10) again: ${fibonacci(10)}`);  // 从缓存获取
```
</PythonEditor>

## 高阶函数和函数式编程

### 高阶函数模式

<PythonEditor title="高阶函数" compare={true}>
```python !! py
# Python 高阶函数和函数式编程

# 1. 内置高阶函数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# map: 应用函数到每个元素
squared = list(map(lambda x: x**2, numbers))
print(f"Squared: {squared}")

# filter: 过滤元素
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")

# reduce: 累积操作
from functools import reduce
sum_all = reduce(lambda acc, x: acc + x, numbers, 0)
product_all = reduce(lambda acc, x: acc * x, numbers, 1)
print(f"Sum: {sum_all}, Product: {product_all}")

# 2. 自定义高阶函数
def apply_twice(func, value):
    """应用函数两次"""
    return func(func(value))

def add_one(x):
    return x + 1

result = apply_twice(add_one, 5)  # ((5 + 1) + 1) = 7
print(f"Apply twice: {result}")

# 3. 函数组合
def compose(f, g):
    """函数组合：f(g(x))"""
    return lambda x: f(g(x))

def multiply_by_2(x):
    return x * 2

def subtract_1(x):
    return x - 1

# 组合函数：先乘以2，再减1
composed = compose(subtract_1, multiply_by_2)
result = composed(5)  # (5 * 2) - 1 = 9
print(f"Composed function: {result}")

# 4. 多函数组合
def pipe(*functions):
    """管道操作：从左到右应用函数"""
    return lambda x: reduce(lambda acc, func: func(acc), functions, x)

# 创建处理管道
process = pipe(
    lambda x: x * 2,      # 乘以2
    lambda x: x + 10,     # 加10
    lambda x: x ** 2      # 平方
)

result = process(3)  # ((3 * 2) + 10) ** 2 = 16 ** 2 = 256
print(f"Pipeline result: {result}")

# 5. 装饰器作为高阶函数
def log_calls(func):
    """记录函数调用的装饰器"""
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned: {result}")
        return result
    return wrapper

def retry(max_attempts=3):
    """重试装饰器工厂"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts - 1:
                        raise
                    print(f"Attempt {attempt + 1} failed: {e}")
            
        return wrapper
    return decorator

@log_calls
@retry(max_attempts=2)
def risky_operation(x, y):
    """可能失败的操作"""
    if x < 0:
        raise ValueError("x cannot be negative")
    return x / y

try:
    result = risky_operation(10, 2)
    print(f"Risky operation result: {result}")
except Exception as e:
    print(f"Operation failed: {e}")

# 6. 柯里化实现
def curry(func):
    """柯里化函数"""
    def curried(*args, **kwargs):
        if len(args) + len(kwargs) >= func.__code__.co_argcount:
            return func(*args, **kwargs)
        return lambda *more_args, **more_kwargs: curried(*(args + more_args), **{**kwargs, **more_kwargs})
    return curried

@curry
def add_three(a, b, c):
    return a + b + c

# 使用柯里化函数
add_1_2 = add_three(1, 2)
result = add_1_2(3)  # 6
print(f"Curried function: {result}")

# 7. 偏函数应用
from functools import partial

def multiply(x, y, z):
    return x * y * z

# 创建偏函数
double = partial(multiply, 2)      # 固定第一个参数为2
result = double(3, 4)              # 2 * 3 * 4 = 24
print(f"Partial function: {result}")

# 8. 函数式数据处理
def process_data(data):
    """函数式数据处理流水线"""
    return pipe(
        lambda items: filter(lambda x: x > 0, items),           # 过滤正数
        lambda items: map(lambda x: x * 2, items),              # 乘以2
        lambda items: filter(lambda x: x % 4 == 0, items),      # 过滤能被4整除的
        list                                                    # 转换为列表
    )(data)

test_data = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
processed = process_data(test_data)
print(f"Processed data: {processed}")

# 9. 递归高阶函数
def fold_right(func, initial, iterable):
    """右折叠操作"""
    items = list(iterable)
    if not items:
        return initial
    return func(items[0], fold_right(func, initial, items[1:]))

def fold_left(func, initial, iterable):
    """左折叠操作"""
    result = initial
    for item in iterable:
        result = func(result, item)
    return result

# 测试折叠操作
numbers = [1, 2, 3, 4, 5]
sum_right = fold_right(lambda x, acc: x + acc, 0, numbers)
sum_left = fold_left(lambda acc, x: acc + x, 0, numbers)
print(f"Right fold sum: {sum_right}")
print(f"Left fold sum: {sum_left}")

# 10. 生成器和高阶函数
def generate_fibonacci():
    """斐波那契数列生成器"""
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

def take(n, iterable):
    """取前n个元素"""
    for i, item in enumerate(iterable):
        if i >= n:
            break
        yield item

def map_gen(func, iterable):
    """惰性map操作"""
    for item in iterable:
        yield func(item)

# 使用生成器的函数式操作
fib_squares = map_gen(lambda x: x**2, take(10, generate_fibonacci()))
result = list(fib_squares)
print(f"First 10 Fibonacci squares: {result}")
```

```javascript !! js
// JavaScript 高阶函数和函数式编程

// 1. 数组的内置高阶函数
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// map: 应用函数到每个元素
const squared = numbers.map(x => x ** 2);
console.log(`Squared: ${squared}`);

// filter: 过滤元素
const evens = numbers.filter(x => x % 2 === 0);
console.log(`Evens: ${evens}`);

// reduce: 累积操作
const sumAll = numbers.reduce((acc, x) => acc + x, 0);
const productAll = numbers.reduce((acc, x) => acc * x, 1);
console.log(`Sum: ${sumAll}, Product: ${productAll}`);

// forEach: 副作用操作
console.log("Numbers:");
numbers.forEach((num, index) => {
    console.log(`${index}: ${num}`);
});

// 2. 自定义高阶函数
function applyTwice(func, value) {
    return func(func(value));
}

const addOne = x => x + 1;
const result1 = applyTwice(addOne, 5);  // ((5 + 1) + 1) = 7
console.log(`Apply twice: ${result1}`);

// 3. 函数组合
const compose = (f, g) => x => f(g(x));

const multiplyBy2 = x => x * 2;
const subtract1 = x => x - 1;

// 组合函数：先乘以2，再减1
const composed = compose(subtract1, multiplyBy2);
const result2 = composed(5);  // (5 * 2) - 1 = 9
console.log(`Composed function: ${result2}`);

// 4. 多函数组合（管道操作）
const pipe = (...functions) => x => functions.reduce((acc, func) => func(acc), x);

// 创建处理管道
const process = pipe(
    x => x * 2,      // 乘以2
    x => x + 10,     // 加10
    x => x ** 2      // 平方
);

const result3 = process(3);  // ((3 * 2) + 10) ** 2 = 16 ** 2 = 256
console.log(`Pipeline result: ${result3}`);

// 5. 装饰器模式的高阶函数
function logCalls(func) {
    return function(...args) {
        console.log(`Calling ${func.name} with args: ${args}`);
        const result = func.apply(this, args);
        console.log(`${func.name} returned: ${result}`);
        return result;
    };
}

function retry(maxAttempts = 3) {
    return function(func) {
        return function(...args) {
            for (let attempt = 0; attempt < maxAttempts; attempt++) {
                try {
                    return func.apply(this, args);
                } catch (error) {
                    if (attempt === maxAttempts - 1) {
                        throw error;
                    }
                    console.log(`Attempt ${attempt + 1} failed: ${error.message}`);
                }
            }
        };
    };
}

// 应用装饰器
const riskyOperation = retry(2)(logCalls(function riskyOp(x, y) {
    if (x < 0) {
        throw new Error("x cannot be negative");
    }
    return x / y;
}));

try {
    const result = riskyOperation(10, 2);
    console.log(`Risky operation result: ${result}`);
} catch (error) {
    console.log(`Operation failed: ${error.message}`);
}

// 6. 柯里化实现
function curry(fn) {
    return function curried(...args) {
        if (args.length >= fn.length) {
            return fn.apply(this, args);
        } else {
            return function(...args2) {
                return curried.apply(this, args.concat(args2));
            };
        }
    };
}

const addThree = (a, b, c) => a + b + c;
const curriedAddThree = curry(addThree);

// 使用柯里化函数
const add12 = curriedAddThree(1, 2);
const result4 = add12(3);  // 6
console.log(`Curried function: ${result4}`);

// 自动柯里化的语法糖
const curriedMultiply = a => b => c => a * b * c;
const result5 = curriedMultiply(2)(3)(4);  // 24
console.log(`Auto-curried: ${result5}`);

// 7. 偏函数应用
function partial(fn, ...partialArgs) {
    return function(...remainingArgs) {
        return fn(...partialArgs, ...remainingArgs);
    };
}

const multiply = (x, y, z) => x * y * z;

// 创建偏函数
const double = partial(multiply, 2);      // 固定第一个参数为2
const result6 = double(3, 4);             // 2 * 3 * 4 = 24
console.log(`Partial function: ${result6}`);

// 8. 函数式数据处理
function processData(data) {
    return data
        .filter(x => x > 0)           // 过滤正数
        .map(x => x * 2)              // 乘以2
        .filter(x => x % 4 === 0);    // 过滤能被4整除的
}

const testData = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8];
const processed = processData(testData);
console.log(`Processed data: ${processed}`);

// 9. 函数式编程工具函数
const FP = {
    // 惰性求值
    lazy(fn) {
        let cached = false;
        let result;
        
        return function() {
            if (!cached) {
                result = fn.apply(this, arguments);
                cached = true;
            }
            return result;
        };
    },
    
    // 记忆化
    memoize(fn) {
        const cache = new Map();
        
        return function(...args) {
            const key = JSON.stringify(args);
            
            if (cache.has(key)) {
                return cache.get(key);
            }
            
            const result = fn.apply(this, args);
            cache.set(key, result);
            return result;
        };
    },
    
    // 防抖
    debounce(fn, delay) {
        let timeoutId;
        
        return function(...args) {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => fn.apply(this, args), delay);
        };
    },
    
    // 节流
    throttle(fn, limit) {
        let inThrottle;
        
        return function(...args) {
            if (!inThrottle) {
                fn.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
};

// 测试工具函数
const expensiveCalculation = FP.memoize(function(n) {
    console.log(`Computing fibonacci(${n})`);
    if (n < 2) return n;
    return expensiveCalculation(n - 1) + expensiveCalculation(n - 2);
});

console.log(`Fibonacci(10): ${expensiveCalculation(10)}`);
console.log(`Fibonacci(10) again: ${expensiveCalculation(10)}`);  // 从缓存获取

// 10. 函数式数据结构
class FunctionalArray {
    constructor(items = []) {
        this.items = [...items];
    }
    
    map(fn) {
        return new FunctionalArray(this.items.map(fn));
    }
    
    filter(fn) {
        return new FunctionalArray(this.items.filter(fn));
    }
    
    reduce(fn, initial) {
        return this.items.reduce(fn, initial);
    }
    
    flatMap(fn) {
        return new FunctionalArray(this.items.flatMap(fn));
    }
    
    take(n) {
        return new FunctionalArray(this.items.slice(0, n));
    }
    
    drop(n) {
        return new FunctionalArray(this.items.slice(n));
    }
    
    toArray() {
        return [...this.items];
    }
    
    // 支持链式调用
    pipe(...functions) {
        return functions.reduce((acc, func) => func(acc), this);
    }
}

// 使用函数式数组
const functionalResult = new FunctionalArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    .filter(x => x % 2 === 0)     // [2, 4, 6, 8, 10]
    .map(x => x * x)              // [4, 16, 36, 64, 100]
    .take(3)                      // [4, 16, 36]
    .toArray();

console.log(`Functional array result: ${functionalResult}`);

// 11. 异步高阶函数
async function asyncMap(array, asyncFn) {
    const promises = array.map(asyncFn);
    return Promise.all(promises);
}

async function asyncFilter(array, asyncPredicate) {
    const results = await asyncMap(array, asyncPredicate);
    return array.filter((_, index) => results[index]);
}

// 模拟异步操作
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function isEvenAsync(num) {
    await delay(10);  // 模拟异步操作
    return num % 2 === 0;
}

async function doubleAsync(num) {
    await delay(10);  // 模拟异步操作
    return num * 2;
}

// 使用异步高阶函数
(async () => {
    const nums = [1, 2, 3, 4, 5];
    
    const evens = await asyncFilter(nums, isEvenAsync);
    console.log(`Async filtered evens: ${evens}`);
    
    const doubled = await asyncMap(nums, doubleAsync);
    console.log(`Async mapped doubled: ${doubled}`);
})();
```
</PythonEditor>

## 函数性能和优化

### 函数调用优化

<PythonEditor title="函数性能优化" compare={true}>
```python !! py
# Python 函数性能优化

import time
import functools
from typing import Any, Callable

# 1. 函数调用开销测量
def measure_time(func: Callable) -> Callable:
    """测量函数执行时间的装饰器"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        result = func(*args, **kwargs)
        end_time = time.perf_counter()
        print(f"{func.__name__} took {(end_time - start_time) * 1000:.4f} ms")
        return result
    return wrapper

# 2. 记忆化优化递归
def memoize(func: Callable) -> Callable:
    """记忆化装饰器"""
    cache = {}
    
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # 创建缓存键
        key = str(args) + str(sorted(kwargs.items()))
        
        if key not in cache:
            cache[key] = func(*args, **kwargs)
        
        return cache[key]
    
    wrapper.cache = cache
    wrapper.cache_clear = lambda: cache.clear()
    return wrapper

# 使用内置的 lru_cache（更高效）
@functools.lru_cache(maxsize=128)
def fibonacci_cached(n: int) -> int:
    """缓存的斐波那契函数"""
    if n < 2:
        return n
    return fibonacci_cached(n - 1) + fibonacci_cached(n - 2)

@measure_time
def fibonacci_naive(n: int) -> int:
    """朴素递归斐波那契"""
    if n < 2:
        return n
    return fibonacci_naive(n - 1) + fibonacci_naive(n - 2)

@measure_time
@memoize
def fibonacci_memoized(n: int) -> int:
    """记忆化递归斐波那契"""
    if n < 2:
        return n
    return fibonacci_memoized(n - 1) + fibonacci_memoized(n - 2)

# 性能对比
print("Computing Fibonacci(35):")
print(f"Naive: {fibonacci_naive(35)}")
print(f"Memoized: {fibonacci_memoized(35)}")
print(f"LRU Cache: {fibonacci_cached(35)}")

# 3. 尾递归优化（Python 不支持，但可以模拟）
def tail_recursive(func: Callable) -> Callable:
    """尾递归优化装饰器（trampolineֱ）"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        while callable(result):
            result = result()
        return result
    return wrapper

@tail_recursive
def factorial_tail(n: int, acc: int = 1) -> Any:
    """尾递归优化的阶乘"""
    if n <= 1:
        return acc
    return lambda: factorial_tail(n - 1, n * acc)

@measure_time
def test_factorial():
    """测试阶乘性能"""
    return factorial_tail(1000)

print(f"\nTail recursive factorial(1000): {test_factorial()}")

# 4. 函数内联和局部优化
@measure_time
def sum_squares_optimized(numbers: list) -> int:
    """优化的平方和计算"""
    total = 0
    # 避免重复的属性查找
    append = total.__add__
    
    for num in numbers:
        total += num * num
    
    return total

@measure_time
def sum_squares_naive(numbers: list) -> int:
    """朴素的平方和计算"""
    return sum(x * x for x in numbers)

# 性能测试
large_numbers = list(range(100000))
print(f"\nSum of squares for {len(large_numbers)} numbers:")
result1 = sum_squares_optimized(large_numbers)
result2 = sum_squares_naive(large_numbers)

# 5. 生成器优化内存使用
def process_large_dataset_memory_efficient(data_source: Callable):
    """内存高效的数据处理"""
    def processor():
        for item in data_source():
            if item % 2 == 0:  # 只处理偶数
                yield item * item
    
    return processor

def process_large_dataset_memory_hungry(data_source: Callable):
    """内存消耗大的数据处理"""
    data = list(data_source())
    filtered = [x for x in data if x % 2 == 0]
    return [x * x for x in filtered]

def large_data_source():
    """大数据源生成器"""
    for i in range(1000000):
        yield i

# 6. 函数对象池化
class FunctionPool:
    """函数对象池"""
    def __init__(self, factory: Callable, max_size: int = 10):
        self.factory = factory
        self.max_size = max_size
        self.pool = []
    
    def get(self):
        if self.pool:
            return self.pool.pop()
        return self.factory()
    
    def put(self, obj):
        if len(self.pool) < self.max_size:
            self.pool.append(obj)

# 7. 批处理优化
def batch_process(items: list, batch_size: int = 1000) -> list:
    """批处理优化"""
    results = []
    
    for i in range(0, len(items), batch_size):
        batch = items[i:i + batch_size]
        # 批量处理减少函数调用开销
        batch_result = [x * x for x in batch]
        results.extend(batch_result)
    
    return results

# 8. 编译时优化（使用 numba 等库）
try:
    from numba import jit
    
    @jit(nopython=True)
    def compute_intensive_jit(n: int) -> float:
        """JIT 编译的计算密集函数"""
        result = 0.0
        for i in range(n):
            result += i * i * 3.14159
        return result
    
    @measure_time
    def test_jit():
        return compute_intensive_jit(1000000)
    
    print(f"\nJIT compiled result: {test_jit()}")
    
except ImportError:
    print("Numba not available for JIT compilation")

# 9. 缓存策略比较
class CacheStrategy:
    """不同缓存策略的比较"""
    
    @staticmethod
    @functools.lru_cache(maxsize=128)
    def expensive_operation_lru(x: int) -> int:
        """LRU 缓存的昂贵操作"""
        time.sleep(0.01)  # 模拟昂贵操作
        return x * x * x
    
    @staticmethod
    def expensive_operation_dict():
        """字典缓存的昂贵操作"""
        cache = {}
        
        def inner(x: int) -> int:
            if x not in cache:
                time.sleep(0.01)  # 模拟昂贵操作
                cache[x] = x * x * x
            return cache[x]
        
        return inner

# 测试缓存策略
dict_cached_func = CacheStrategy.expensive_operation_dict()

@measure_time
def test_lru_cache():
    for i in range(100):
        CacheStrategy.expensive_operation_lru(i % 10)

@measure_time
def test_dict_cache():
    for i in range(100):
        dict_cached_func(i % 10)

print("\nCache strategy comparison:")
test_lru_cache()
test_dict_cache()

# 10. 函数调用分析
def profile_function_calls(func: Callable) -> Callable:
    """分析函数调用的装饰器"""
    call_count = 0
    total_time = 0
    
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        nonlocal call_count, total_time
        
        start_time = time.perf_counter()
        result = func(*args, **kwargs)
        end_time = time.perf_counter()
        
        call_count += 1
        total_time += (end_time - start_time)
        
        return result
    
    def get_stats():
        avg_time = total_time / call_count if call_count > 0 else 0
        return {
            'call_count': call_count,
            'total_time': total_time,
            'average_time': avg_time
        }
    
    wrapper.get_stats = get_stats
    return wrapper

@profile_function_calls
def example_function(n: int) -> int:
    """示例函数"""
    return sum(range(n))

# 测试函数调用分析
for i in range(100):
    example_function(i * 100)

stats = example_function.get_stats()
print(f"\nFunction call analysis:")
print(f"Total calls: {stats['call_count']}")
print(f"Total time: {stats['total_time']:.6f} seconds")
print(f"Average time: {stats['average_time']:.6f} seconds")
```

```javascript !! js
// JavaScript 函数性能优化

// 1. 函数调用开销测量
function measureTime(func) {
    return function(...args) {
        const startTime = performance.now();
        const result = func.apply(this, args);
        const endTime = performance.now();
        console.log(`${func.name} took ${(endTime - startTime).toFixed(4)} ms`);
        return result;
    };
}

// 2. 记忆化优化递归
function memoize(func) {
    const cache = new Map();
    
    return function(...args) {
        const key = JSON.stringify(args);
        
        if (cache.has(key)) {
            return cache.get(key);
        }
        
        const result = func.apply(this, args);
        cache.set(key, result);
        return result;
    };
}

// 更高效的记忆化（使用 WeakMap 和原始值分离）
function advancedMemoize(func) {
    const cache = new Map();
    const objectCache = new WeakMap();
    
    return function(...args) {
        // 区分原始值和对象
        const primitiveArgs = args.filter(arg => typeof arg !== 'object' || arg === null);
        const objectArgs = args.filter(arg => typeof arg === 'object' && arg !== null);
        
        let currentCache = cache;
        
        // 处理原始值
        const primitiveKey = JSON.stringify(primitiveArgs);
        if (!currentCache.has(primitiveKey)) {
            currentCache.set(primitiveKey, new Map());
        }
        currentCache = currentCache.get(primitiveKey);
        
        // 处理对象（使用 WeakMap）
        for (const obj of objectArgs) {
            if (!objectCache.has(obj)) {
                objectCache.set(obj, new Map());
            }
            if (!currentCache.has(obj)) {
                currentCache.set(obj, objectCache.get(obj));
            }
            currentCache = currentCache.get(obj);
        }
        
        if (!currentCache.has('result')) {
            currentCache.set('result', func.apply(this, args));
        }
        
        return currentCache.get('result');
    };
}

// 斐波那契函数性能比较
const fibonacciNaive = measureTime(function fibonacciNaive(n) {
    if (n < 2) return n;
    return fibonacciNaive(n - 1) + fibonacciNaive(n - 2);
});

const fibonacciMemoized = memoize(function fibonacci(n) {
    if (n < 2) return n;
    return fibonacciMemoized(n - 1) + fibonacciMemoized(n - 2);
});

// 测试性能
console.log("Computing Fibonacci(40):");
console.log(`Memoized: ${fibonacciMemoized(40)}`);
// console.log(`Naive: ${fibonacciNaive(40)}`); // 太慢，注释掉

// 3. 尾递归优化（蹦床函数）
function trampoline(func) {
    return function(...args) {
        let result = func.apply(this, args);
        while (typeof result === 'function') {
            result = result();
        }
        return result;
    };
}

const factorialTail = trampoline(function factorial(n, acc = 1) {
    if (n <= 1) {
        return acc;
    }
    return () => factorial(n - 1, n * acc);
});

const testFactorial = measureTime(function() {
    return factorialTail(1000);
});

console.log(`\nTail recursive factorial(1000): ${testFactorial()}`);

// 4. 函数内联和局部优化
const sumSquaresOptimized = measureTime(function sumSquaresOptimized(numbers) {
    let total = 0;
    const length = numbers.length;  // 缓存长度
    
    // 使用传统 for 循环而不是 forEach
    for (let i = 0; i < length; i++) {
        const num = numbers[i];
        total += num * num;
    }
    
    return total;
});

const sumSquaresNaive = measureTime(function sumSquaresNaive(numbers) {
    return numbers.reduce((sum, x) => sum + x * x, 0);
});

// 性能测试
const largeNumbers = Array.from({length: 1000000}, (_, i) => i);
console.log(`\nSum of squares for ${largeNumbers.length} numbers:`);
const result1 = sumSquaresOptimized(largeNumbers);
const result2 = sumSquaresNaive(largeNumbers);

// 5. 生成器优化内存使用
function* processLargeDatasetMemoryEfficient(dataSource) {
    for (const item of dataSource()) {
        if (item % 2 === 0) {  // 只处理偶数
            yield item * item;
        }
    }
}

function processLargeDatasetMemoryHungry(dataSource) {
    const data = Array.from(dataSource());
    const filtered = data.filter(x => x % 2 === 0);
    return filtered.map(x => x * x);
}

function* largeDataSource() {
    for (let i = 0; i < 1000000; i++) {
        yield i;
    }
}

// 6. 对象池化
class ObjectPool {
    constructor(factory, maxSize = 10) {
        this.factory = factory;
        this.maxSize = maxSize;
        this.pool = [];
    }
    
    get() {
        return this.pool.length > 0 ? this.pool.pop() : this.factory();
    }
    
    put(obj) {
        if (this.pool.length < this.maxSize) {
            // 重置对象状态
            if (typeof obj.reset === 'function') {
                obj.reset();
            }
            this.pool.push(obj);
        }
    }
}

// 示例：计算器对象池
class Calculator {
    constructor() {
        this.result = 0;
    }
    
    add(value) {
        this.result += value;
        return this;
    }
    
    multiply(value) {
        this.result *= value;
        return this;
    }
    
    getResult() {
        return this.result;
    }
    
    reset() {
        this.result = 0;
    }
}

const calculatorPool = new ObjectPool(() => new Calculator(), 5);

// 7. 批处理优化
function batchProcess(items, batchSize = 1000) {
    const results = [];
    
    for (let i = 0; i < items.length; i += batchSize) {
        const batch = items.slice(i, i + batchSize);
        // 批量处理减少函数调用开销
        const batchResult = batch.map(x => x * x);
        results.push(...batchResult);
    }
    
    return results;
}

// 8. Web Workers 用于 CPU 密集任务
class WorkerPool {
    constructor(workerScript, poolSize = 4) {
        this.workers = [];
        this.taskQueue = [];
        this.availableWorkers = [];
        
        for (let i = 0; i < poolSize; i++) {
            const worker = new Worker(workerScript);
            worker.onmessage = (event) => {
                const { taskId, result, error } = event.data;
                this.handleWorkerMessage(worker, taskId, result, error);
            };
            this.workers.push(worker);
            this.availableWorkers.push(worker);
        }
    }
    
    execute(data) {
        return new Promise((resolve, reject) => {
            const taskId = Date.now() + Math.random();
            const task = { taskId, data, resolve, reject };
            
            if (this.availableWorkers.length > 0) {
                this.assignTask(task);
            } else {
                this.taskQueue.push(task);
            }
        });
    }
    
    assignTask(task) {
        const worker = this.availableWorkers.pop();
        worker.currentTask = task;
        worker.postMessage({
            taskId: task.taskId,
            data: task.data
        });
    }
    
    handleWorkerMessage(worker, taskId, result, error) {
        const task = worker.currentTask;
        
        if (task && task.taskId === taskId) {
            if (error) {
                task.reject(new Error(error));
            } else {
                task.resolve(result);
            }
            
            worker.currentTask = null;
            this.availableWorkers.push(worker);
            
            // 处理队列中的下一个任务
            if (this.taskQueue.length > 0) {
                const nextTask = this.taskQueue.shift();
                this.assignTask(nextTask);
            }
        }
    }
}

// 9. 缓存策略比较
class CacheStrategy {
    // LRU 缓存实现
    static createLRUCache(maxSize = 100) {
        const cache = new Map();
        
        return function(key, factory) {
            if (cache.has(key)) {
                // 移动到最后（最近使用）
                const value = cache.get(key);
                cache.delete(key);
                cache.set(key, value);
                return value;
            }
            
            const value = factory();
            
            if (cache.size >= maxSize) {
                // 删除最旧的条目
                const firstKey = cache.keys().next().value;
                cache.delete(firstKey);
            }
            
            cache.set(key, value);
            return value;
        };
    }
    
    // 时间过期缓存
    static createTTLCache(ttl = 60000) {  // 60秒
        const cache = new Map();
        
        return function(key, factory) {
            const now = Date.now();
            
            if (cache.has(key)) {
                const { value, timestamp } = cache.get(key);
                if (now - timestamp < ttl) {
                    return value;
                }
                cache.delete(key);
            }
            
            const value = factory();
            cache.set(key, { value, timestamp: now });
            return value;
        };
    }
}

// 10. 性能监控和分析
class PerformanceMonitor {
    constructor() {
        this.metrics = new Map();
    }
    
    wrap(func, name = func.name) {
        const self = this;
        
        return function(...args) {
            const startTime = performance.now();
            const startMemory = performance.memory ? performance.memory.usedJSHeapSize : 0;
            
            try {
                const result = func.apply(this, args);
                
                if (result instanceof Promise) {
                    return result.finally(() => {
                        self.recordMetrics(name, startTime, startMemory);
                    });
                } else {
                    self.recordMetrics(name, startTime, startMemory);
                    return result;
                }
            } catch (error) {
                self.recordMetrics(name, startTime, startMemory, error);
                throw error;
            }
        };
    }
    
    recordMetrics(name, startTime, startMemory, error = null) {
        const endTime = performance.now();
        const endMemory = performance.memory ? performance.memory.usedJSHeapSize : 0;
        
        if (!this.metrics.has(name)) {
            this.metrics.set(name, {
                callCount: 0,
                totalTime: 0,
                totalMemory: 0,
                errors: 0,
                minTime: Infinity,
                maxTime: 0
            });
        }
        
        const metrics = this.metrics.get(name);
        const duration = endTime - startTime;
        const memoryUsed = endMemory - startMemory;
        
        metrics.callCount++;
        metrics.totalTime += duration;
        metrics.totalMemory += memoryUsed;
        metrics.minTime = Math.min(metrics.minTime, duration);
        metrics.maxTime = Math.max(metrics.maxTime, duration);
        
        if (error) {
            metrics.errors++;
        }
    }
    
    getReport() {
        const report = {};
        
        for (const [name, metrics] of this.metrics) {
            report[name] = {
                callCount: metrics.callCount,
                averageTime: metrics.totalTime / metrics.callCount,
                totalTime: metrics.totalTime,
                minTime: metrics.minTime,
                maxTime: metrics.maxTime,
                averageMemory: metrics.totalMemory / metrics.callCount,
                errorRate: metrics.errors / metrics.callCount
            };
        }
        
        return report;
    }
}

// 使用性能监控
const monitor = new PerformanceMonitor();

const monitoredFunction = monitor.wrap(function expensiveOperation(n) {
    let result = 0;
    for (let i = 0; i < n; i++) {
        result += Math.sqrt(i) * Math.sin(i);
    }
    return result;
}, 'expensiveOperation');

// 执行多次以收集指标
for (let i = 0; i < 10; i++) {
    monitoredFunction(100000);
}

console.log('\nPerformance Report:');
console.log(JSON.stringify(monitor.getReport(), null, 2));
```
</PythonEditor>

## 总结

本模块深入比较了 Python 和 JavaScript 的函数机制：

### 主要差异：

1. **函数定义**: JavaScript 有多种定义方式（声明、表达式、箭头函数），Python 主要使用 `def` 和 `lambda`
2. **作用域规则**: JavaScript 有函数作用域和块级作用域，Python 有 LEGB 规则
3. **变量提升**: JavaScript 存在提升现象，Python 没有
4. **参数处理**: JavaScript 使用解构和剩余参数，Python 使用 `*args` 和 `**kwargs`
5. **闭包行为**: 两者都支持闭包，但在循环变量捕获上有不同的陷阱

### 关键概念：

1. **this 绑定**: JavaScript 特有的动态 this 绑定机制
2. **箭头函数**: JavaScript ES6+ 的简化语法和词法 this
3. **高阶函数**: 两种语言都支持函数式编程模式
4. **性能优化**: 记忆化、尾递归优化、批处理等技术

理解这些函数机制差异对于有效地从 Python 过渡到 JavaScript 开发至关重要。下一个模块将探讨异步编程这个 JavaScript 的核心特性。
